<template>
    <div>
<!--      // 面包屑-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
<!--      // 角色列表卡片-->
      <el-card>
<!--        // 添加角色按钮-->
        <el-button type="primary">添加角色</el-button>

        <el-table :data="rolesList" border style="width: 100%" stripe>
          <!--        // 展开列    -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row :class="['row_center','dbBot', index === 0 ? 'dbTop' : '']" v-for="(item1, index) in scope.row.children" :key="item1.id">
                <!-- // 渲染一级权限-->
                <el-col :span="5">
                  <el-tag @close="deleteItem(scope.row,item1.id)" closable>{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- // 渲染二，三级权限-->
                <el-col :span="19">
                  <!-- // 通过v-for循环渲染 二级权限-->
                  <el-row :class="['row_center',index2 === 0 ? '' : 'dbTop']" v-for="(item2,index2) in item1.children" :key="item2.id">
                    <el-col :span="6">
                      <el-tag @close="deleteItem(scope.row,item2.id)" type="success" closable>{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag @close="deleteItem(scope.row,item3.id)" closable type="warning" v-for="item3 in item2.children" :key="item3.id">{{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <!--        // 索引列    -->
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column prop="roleName" label="角色名称"></el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
          <el-table-column  label="操作">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRights(scope.row)">分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!--      // 展示权限对话框 -->
      <el-dialog title="分配权限" :visible.sync="rightDialog" width="40%" @close="treeClose">
        <!--     // 树形控件   -->
        <el-tree ref="treeRef" :data="rightsList" :props="treeProps" :default-checked-keys="rightsKey" default-expand-all show-checkbox node-key="id"></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="rightDialog = false">取 消</el-button>
          <el-button type="primary" @click="checkHandle">确 定</el-button>
       </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表数据
      rolesList: [],
      // 控制分配权限对话框的显示隐藏
      rightDialog: false,
      // 获取所有的权限数据
      rightsList: [],
      // 树形控件属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认展开的节点的 key 的数组
      rightsKey: [],
      // 角色ID
      roleId: ''
    }
  },
  created() {
    // 初始化 角色列表数据
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: result } = await this.$http.get('roles')
      if (result.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = result.data
      console.log(result)
    },
    // 删除权限
    deleteItem(role, rightId) {
      this.$confirm('是否永久删除此权限?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {
        const { data: result } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if (result.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        // 防止重新刷新页面
        // this.getRolesList()
        role.children = result.data
      }).catch(() => {
        this.$message.info('取消了删除操作')
      })
    },
    // 展示分配权限的对话框
    async showSetRights(node) {
      this.roleId = node.id
      const { data: result } = await this.$http.get('rights/tree')
      if (result.meta.status !== 200) return this.$message.error('获取权限失败')
      this.rightsList = result.data
      this.rightDialog = !this.rightDialog
      this.getleafKeys(node, this.rightsKey)
    },
    // 通过递归的形式，获取角色下所有三级权限的ID，并保存到rightsKey中
    getleafKeys(node, arr) {
      // 如果当前node 不包括children 属性，则是三级节点
      if (!node.children) return arr.push(node.id)

      node.children.forEach(item => {
        this.getleafKeys(item, arr)
      })
    },
    // 关闭Tree 重置rightsKey: []
    treeClose() {
      this.rightsKey = []
    },
    // 点击为角色添加权限
    async checkHandle() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]

      const idStr = keys.join(',')

      const { data: result } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })

      if (result.meta.status !== 200) return this.$message.error('添加权限失败')

      this.$message.success('添加权限成功')
      this.rightDialog = !this.rightDialog
      this.getRolesList()
    }
  }
}
</script>

<style scoped lang="less">
.el-tag {
  margin: 8px;
}
.dbTop {
  border-top: 1px solid #eee;
}
.dbBot {
  border-bottom: 1px solid #eee;
}
.row_center {
  display: flex;
  align-items: center;
}
</style>
